﻿// StaticLib1.cpp : 定义静态库的函数。
//

#include "pch.h"
#include "framework.h"
#include "output.h"

// TODO: 这是一个库函数示例
void fnStaticLib1()
{
}



#include "output.h"
#include "../SystemInfo/core/SystemInfo.h"
#include "../SystemInfo/core/sysinfo.h"
#include <stdio.h>
#include "../SystemInfo/util/utility.h"
#include <array>
#include <intrin.h>    // 所有Intrinsics函数

int CpuId(wchar_t *buf)
{
	std::array<int, 4> cpui;    //#include <array>
	// Calling __cpuid with 0x0 as the function_id argument  
	// gets the number of the highest valid function ID.  什么是function ID？
	__cpuid(cpui.data(), 0x0);    //cpui[0] = "funcition_id的最大值"
	int nIds_ = cpui[0];
	//保存遍历到的所有cpui的值 
	std::vector<std::array<int, 4>> data_;
	for (int i = 0; i <= nIds_; ++i)
	{
		__cpuidex(cpui.data(), i, 0);
		data_.push_back(cpui);
	}
	//reinterpret_cast<int*>(vendor) //*reinterpret_cast<int*>(vendor)
	//索引0 0+4 0+8的值构成了CPU芯片的名称
	char vendor[0x20] = { 0 };
	*reinterpret_cast<int*>(vendor) = data_[0][1];
	*reinterpret_cast<int*>(vendor + 4) = data_[0][3];
	*reinterpret_cast<int*>(vendor + 8) = data_[0][2];  // vendor="GenuineIntel"    
	std::string vendor_ = vendor;
	bool isIntel_ = false;
	bool isAMD = false;
	if ("GenuineIntel" == vendor_)
	{
		isIntel_ = true;    //厂商为INTEL
	}
	else if ("AuthenticAMD" == vendor_)
	{
		isAMD = true;       //厂商为AMD
	}
	/***
	*/
	char vendor_serialnumber[0x14] = { 0 };
	sprintf_s(vendor_serialnumber, sizeof(vendor_serialnumber), "%08X%08X", data_[1][3], data_[1][0]);
	//用“wmic cpu get processorid”获取的结果进行比对，结果应该是一致的。    //vendor_serialnumber = "BFEBFBFF000406E3";    
	//std::cout << "ProcessorId is [ " << vendor_serialnumber << " ]" << std::endl;
	//size_t converted;
	//WCHAR wvender[255];
	//mbstowcs_s(&converted, buf, 255, vendor_serialnumber, 255);
	MultiByteToWideChar(CP_ACP, 0, vendor_serialnumber, 255, buf, 255);
	//MessageBox(0, wvender, L"123", MB_OK);
	return 0;
}

#include <snmp.h>
#include <winsock.h>
#pragma comment(lib, "snmpapi.lib")
#pragma comment(lib, "Ws2_32.lib")

bool GetMacBySNMP(wchar_t * macOUT)
{
	bool ret = false;
	WSADATA WinsockData;
	if (WSAStartup(MAKEWORD(2, 0), &WinsockData) != 0)
		return false;

	// Load the SNMP dll and get the addresses of the functions necessary
	const HINSTANCE m_dll = LoadLibrary(L"inetmib1.dll");
	if (m_dll < (HINSTANCE)HINSTANCE_ERROR)
		return false;

	const PFNSNMPEXTENSIONINIT f_SnmpExtensionInit = (PFNSNMPEXTENSIONINIT)GetProcAddress(m_dll, "SnmpExtensionInit");
	const PFNSNMPEXTENSIONINITEX f_SnmpExtensionInitEx = (PFNSNMPEXTENSIONINITEX)GetProcAddress(m_dll, "SnmpExtensionInitEx");
	const PFNSNMPEXTENSIONQUERY f_SnmpExtensionQuery = (PFNSNMPEXTENSIONQUERY)GetProcAddress(m_dll, "SnmpExtensionQuery");
	const PFNSNMPEXTENSIONTRAP f_SnmpExtensionTrap = (PFNSNMPEXTENSIONTRAP)GetProcAddress(m_dll, "SnmpExtensionTrap");
	HANDLE pollForTrapEvent;
	AsnObjectIdentifier supportedView;
	f_SnmpExtensionInit(GetTickCount(), &pollForTrapEvent, &supportedView);

	// Initialize the variable list to be retrieved by f_SnmpExtensionQuery
	const AsnObjectIdentifier MIB_NULL = { 0, 0 };

	RFC1157VarBind varBind[2];
	varBind[0].name = MIB_NULL;
	varBind[1].name = MIB_NULL;

	RFC1157VarBindList varBindList;
	varBindList.list = varBind;

	UINT OID_ifEntryType[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 3 };
	UINT OID_ifEntryNum[] = { 1, 3, 6, 1, 2, 1, 2, 1 };
	UINT OID_ipMACEntAddr[] = { 1, 3, 6, 1, 2, 1, 2, 2, 1, 6 };
	AsnObjectIdentifier MIB_ifMACEntAddr = { sizeof(OID_ipMACEntAddr) / sizeof(UINT), OID_ipMACEntAddr };
	AsnObjectIdentifier MIB_ifEntryType = { sizeof(OID_ifEntryType) / sizeof(UINT), OID_ifEntryType };
	AsnObjectIdentifier MIB_ifEntryNum = { sizeof(OID_ifEntryNum) / sizeof(UINT), OID_ifEntryNum };

	// Copy in the OID to find the number of entries in the Inteface table
	varBindList.len = 1;        // Only retrieving one item
	SnmpUtilOidCpy(&varBind[0].name, &MIB_ifEntryNum);
	AsnInteger errorStatus;
	AsnInteger errorIndex;
	f_SnmpExtensionQuery(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus, &errorIndex);
	varBindList.len = 2;

	// Copy in the OID of ifType, the type of interface
	SnmpUtilOidCpy(&varBind[0].name, &MIB_ifEntryType);

	// Copy in the OID of ifPhysAddress, the address
	SnmpUtilOidCpy(&varBind[1].name, &MIB_ifMACEntAddr);

	for (int j = 0; j < varBind[0].value.asnValue.number; j++)
	{
		// Submit the query.  Responses will be loaded into varBindList.
		// We can expect this call to succeed a # of times corresponding to the # of adapters reported to be in the system
		if (f_SnmpExtensionQuery(ASN_RFC1157_GETNEXTREQUEST, &varBindList, &errorStatus, &errorIndex) == FALSE)
			continue;
		// Confirm that the proper type has been returned
		if (SnmpUtilOidNCmp(&varBind[0].name, &MIB_ifEntryType, MIB_ifEntryType.idLength) != 0)
			continue;
		// Type 6 describes ethernet interfaces
		if (varBind[0].value.asnValue.number != 6)
			continue;
		// Confirm that we have an address here
		if (SnmpUtilOidNCmp(&varBind[1].name, &MIB_ifMACEntAddr, MIB_ifMACEntAddr.idLength) != 0)
			continue;
		if (varBind[1].value.asnValue.address.stream == NULL)
			continue;
		// Ignore all dial-up networking adapters
		if ((varBind[1].value.asnValue.address.stream[0] == 0x44)
			&& (varBind[1].value.asnValue.address.stream[1] == 0x45)
			&& (varBind[1].value.asnValue.address.stream[2] == 0x53)
			&& (varBind[1].value.asnValue.address.stream[3] == 0x54)
			&& (varBind[1].value.asnValue.address.stream[4] == 0x00))
			continue;
		// Ignore NULL addresses returned by other network interfaces
		if ((varBind[1].value.asnValue.address.stream[0] == 0x00)
			&& (varBind[1].value.asnValue.address.stream[1] == 0x00)
			&& (varBind[1].value.asnValue.address.stream[2] == 0x00)
			&& (varBind[1].value.asnValue.address.stream[3] == 0x00)
			&& (varBind[1].value.asnValue.address.stream[4] == 0x00)
			&& (varBind[1].value.asnValue.address.stream[5] == 0x00))
			continue;
		//char buf[32];
		swprintf_s(macOUT, 256, L"%02X-%02X-%02X-%02X-%02X-%02X",
			varBind[1].value.asnValue.address.stream[0],
			varBind[1].value.asnValue.address.stream[1],
			varBind[1].value.asnValue.address.stream[2],
			varBind[1].value.asnValue.address.stream[3],
			varBind[1].value.asnValue.address.stream[4],
			varBind[1].value.asnValue.address.stream[5]);
		ret = true;
		break;
	}

	// Free the bindings
	SnmpUtilVarBindFree(&varBind[0]);
	SnmpUtilVarBindFree(&varBind[1]);
	return ret;
}

////////////////////////////////////////////////////////////////////////////
// 函数名： GetMacByCmd(char *lpszMac)
// 参数：
//      输入： void
//      输出： lpszMac,返回的MAC地址串
// 返回值：
//      TRUE:  获得MAC地址。
//      FALSE: 获取MAC地址失败。
// 过程：
//      1. 创建一个无名管道。
//      2. 创建一个IPCONFIG 的进程，并将输出重定向到管道。
//      3. 从管道获取命令行返回的所有信息放入缓冲区lpszBuffer。
//      4. 从缓冲区lpszBuffer中获得抽取出MAC串。
//
//  提示：可以方便的由此程序获得IP地址等其他信息。
//        对于其他的可以通过其他命令方式得到的信息只需改变strFetCmd 和 
//        str4Search的内容即可。
///////////////////////////////////////////////////////////////////////////

BOOL GetMacByCmd(wchar_t *lpszMac)
{
	const long MAX_COMMAND_SIZE = 10000;

	//获取MAC命令行
	char szFetCmd[] = "ipconfig /all";
	const char* str4Search = "Physical Address. . . . . . . . . : ";

	//初始化返回MAC地址缓冲区
	//memset(lpszMac, 0x00, sizeof(lpszMac));
	BOOL bret;

	SECURITY_ATTRIBUTES sa;
	HANDLE hReadPipe, hWritePipe;

	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = TRUE;

	//创建管道
	bret = CreatePipe(&hReadPipe, &hWritePipe, &sa, 0);
	if (!bret)
	{
		return FALSE;
	}

	//控制命令行窗口信息
	STARTUPINFO si;
	//返回进程信息
	PROCESS_INFORMATION pi;

	si.cb = sizeof(STARTUPINFO);
	GetStartupInfo(&si);
	si.hStdError = hWritePipe;
	si.hStdOutput = hWritePipe;
	si.wShowWindow = SW_HIDE; //隐藏命令行窗口
	si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;

	//创建获取命令行进程
	bret = CreateProcess(NULL, (wchar_t*)L"ipconfig /all", NULL, NULL, TRUE, 0, NULL,
		NULL, &si, &pi);

	char szBuffer[MAX_COMMAND_SIZE + 1]; //放置命令行输出缓冲区
	std::string strBuffer;
	//CString strBuffer;

	if (bret)
	{
		WaitForSingleObject(pi.hProcess, INFINITE);
		unsigned long count;
		CloseHandle(hWritePipe);

		memset(szBuffer, 0x00, sizeof(szBuffer));
		bret = ReadFile(hReadPipe, szBuffer, MAX_COMMAND_SIZE, &count, 0);
		if (!bret)
		{
			//关闭所有的句柄
			CloseHandle(hWritePipe);
			CloseHandle(pi.hProcess);
			CloseHandle(pi.hThread);
			CloseHandle(hReadPipe);
			return FALSE;
		}
		else
		{
			//strBuffer = codecvt::GB2312ToUnicode(szBuffer);
			long ipos;
			ipos = strBuffer.find(str4Search);

			//提取MAC地址串
			strBuffer = strBuffer.substr(ipos + strlen(str4Search));
			ipos = strBuffer.find("/n");
			strBuffer = strBuffer.substr(0, ipos);
		}

	}

	memset(szBuffer, 0x00, sizeof(szBuffer));
	//strcpy(szBuffer, strBuffer.c_str());

	//去掉中间的“00-50-EB-0F-27-82”中间的'-'得到0050EB0F2782
	int j = 0;
	for (int i = 0; i < strlen(szBuffer); i++)
	{
		if (szBuffer[i] != '-')
		{
			lpszMac[j] = szBuffer[i];
			j++;
		}
	}

	//关闭所有的句柄
	CloseHandle(hWritePipe);
	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);
	CloseHandle(hReadPipe);
	return TRUE;

}

bool GetHardwareInfoCompat(HardwareInfo * info)
{
	SystemInfo *localMachine = SystemInfo::getCurrentInstance();
	fillSystemInformationCompat(localMachine->getCurrentInstance());
	SystemInfo *currentMachineInfo = localMachine->getCurrentInstance();
	//currentMachineInfo->getSnapshotGenDateTime();
	//TCHAR biosInfo[256] = { 0 };
	//_tcscat(biosInfo, currentMachineInfo->getBIOS().c_str());
	char hostname[255];
	gethostname(hostname, 255);
	//wchar_t buf[255];
	MultiByteToWideChar(CP_ACP, 0, hostname, 255, info->hostname, 255);
	wchar_t cpuId[256];
	CpuId(cpuId);
	wcscpy_s(info->cpuId, cpuId);
	wcscpy_s(info->bios, currentMachineInfo->getBIOS().c_str());
	wcscpy_s(info->os, currentMachineInfo->getOS().c_str());
	wcscpy_s(info->cpu, currentMachineInfo->getCPU().c_str());
	wcscpy_s(info->mb, currentMachineInfo->getMB().c_str());
	wcscpy_s(info->ram, currentMachineInfo->getRAM().c_str());
	wcscpy_s(info->video, formListString(currentMachineInfo,
		OS_INFO_TYPES::HARDWARE_VIDEO_ADAPTER,
		WRITE_OUT_TYPE::APP_WINDOW).c_str());
	wcscpy_s(info->display, formListString(currentMachineInfo,
		OS_INFO_TYPES::HARDWARE_DISPLAY,
		WRITE_OUT_TYPE::APP_WINDOW).c_str());
	wcscpy_s(info->storage, formListString(currentMachineInfo,
		OS_INFO_TYPES::HARDWARE_STORAGE,
		WRITE_OUT_TYPE::APP_WINDOW).c_str());
	wcscpy_s(info->cdrom, formListString(currentMachineInfo,
		OS_INFO_TYPES::HARDWARE_CDROM,
		WRITE_OUT_TYPE::APP_WINDOW).c_str());
	wcscpy_s(info->network, formListString(currentMachineInfo,
		OS_INFO_TYPES::HARDWARE_NETWORK,
		WRITE_OUT_TYPE::APP_WINDOW).c_str());
	wcscpy_s(info->audio, currentMachineInfo->getAudio().c_str());
	return true;
}

bool GetHardwareInfo(HardwareInfo * info)
{
	SystemInfo *localMachine = SystemInfo::getCurrentInstance();
	if( fillSystemInformation(localMachine->getCurrentInstance()) > 0 )
		return false;
	SystemInfo *currentMachineInfo = localMachine->getCurrentInstance();
	//currentMachineInfo->getSnapshotGenDateTime();
	//TCHAR biosInfo[256] = { 0 };
	//_tcscat(biosInfo, currentMachineInfo->getBIOS().c_str());
	char hostname[255] = {0};
	gethostname(hostname, 255);
	//wchar_t buf[255];
	MultiByteToWideChar(CP_ACP, 0, hostname, 255, info->hostname, 255);
	wchar_t cpuId[256];
	CpuId(cpuId);
	wcscpy_s(info->cpuId, cpuId);
	wcscpy_s(info->bios, currentMachineInfo->getBIOS().c_str());
	wcscpy_s(info->os, currentMachineInfo->getOS().c_str());
	wcscpy_s(info->cpu, currentMachineInfo->getCPU().c_str());
	wcscpy_s(info->mb, currentMachineInfo->getMB().c_str());
	wcscpy_s(info->ram, currentMachineInfo->getRAM().c_str());
	wcscpy_s(info->video, formListString(currentMachineInfo,
		OS_INFO_TYPES::HARDWARE_VIDEO_ADAPTER,
		WRITE_OUT_TYPE::APP_WINDOW).c_str());
	wcscpy_s(info->display, formListString(currentMachineInfo,
		OS_INFO_TYPES::HARDWARE_DISPLAY,
		WRITE_OUT_TYPE::APP_WINDOW).c_str());
	wcscpy_s(info->storage, formListString(currentMachineInfo,
		OS_INFO_TYPES::HARDWARE_STORAGE,
		WRITE_OUT_TYPE::APP_WINDOW).c_str());
	wcscpy_s(info->cdrom, formListString(currentMachineInfo,
		OS_INFO_TYPES::HARDWARE_CDROM,
		WRITE_OUT_TYPE::APP_WINDOW).c_str());
	wcscpy_s(info->network, formListString(currentMachineInfo,
		OS_INFO_TYPES::HARDWARE_NETWORK,
		WRITE_OUT_TYPE::APP_WINDOW).c_str());
	wcscpy_s(info->audio, currentMachineInfo->getAudio().c_str());
	return true;
}
